package com.hwhhhh.mygrad.decoration;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.util.TypedValue;
import android.view.View;

import androidx.annotation.ColorInt;
import androidx.annotation.Dimension;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hwhhhh.mygrad.R;
import com.hwhhhh.mygrad.dto.AppointDTO;
import com.hwhhhh.mygrad.utils.StringUtils;

import java.sql.Date;
import java.util.HashMap;
import java.util.List;

public class HistoryItemDecoration extends RecyclerView.ItemDecoration {

    private HashMap<Integer, Date> titles = new HashMap<>();
    private int titleHeight;
    private int dividerHeight;
    private int dividerWidth;
    private float textHeight;
    private float textBaselineOffset;
    private Drawable mDivider;
    private Paint backgroundPaint, textPaint;
    private Context mContext;


    public HistoryItemDecoration() {
        super();
    }

    public HistoryItemDecoration(Context context, @ColorInt int color, @Dimension float dividerWidth, @Dimension float dividerHeight, List<AppointDTO> data) {
        mDivider = new ColorDrawable(color);
        this.dividerWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,dividerWidth,context.getResources().getDisplayMetrics());
        this.dividerHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,dividerHeight,context.getResources().getDisplayMetrics());
        getTitles(data);
        init(context);
    }

    private void init(Context context) {
        this.mContext = context;
        textPaint = new Paint();
        textPaint.setAntiAlias(true);
        textPaint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 14, mContext.getResources().getDisplayMetrics()));
        textPaint.setColor(mContext.getResources().getColor(R.color.main_font_color));
        Paint.FontMetrics fm = textPaint.getFontMetrics();
        textHeight = fm.bottom - fm.top;//计算文字高度
        textBaselineOffset = fm.bottom;

        backgroundPaint = new Paint();
        backgroundPaint.setAntiAlias(true);
        backgroundPaint.setColor(mContext.getResources().getColor(R.color.login_et));
    }

    @Override
    public void onDraw(@NonNull Canvas c, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        super.onDraw(c, parent, state);
        drawVertical(c, parent);
    }

    @Override
    public void onDrawOver(@NonNull Canvas c, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        super.onDrawOver(c, parent, state);
        int firstVisiblePos = ((LinearLayoutManager) parent.getLayoutManager()).findFirstVisibleItemPosition();
        if(firstVisiblePos == RecyclerView.NO_POSITION){
            return;
        }
        String title = getTitle(firstVisiblePos);
        if(StringUtils.isEmpty(title)){
            return;
        }
        boolean flag = false;
        if(getTitle(firstVisiblePos + 1) != null && !title.equals(getTitle(firstVisiblePos + 1))){
            //说明是当前组最后一个元素，但不一定碰撞了
            View child = parent.findViewHolderForAdapterPosition(firstVisiblePos).itemView;
            if(child.getTop() + child.getMeasuredHeight() < titleHeight){
                //进一步检测碰撞
                c.save();//保存画布当前的状态
                flag = true;
                c.translate(0, child.getTop() + child.getMeasuredHeight() - titleHeight);//负的代表向上
            }
        }
        int left = parent.getPaddingLeft();
        int right = parent.getWidth() - parent.getPaddingRight();
        int top = parent.getPaddingTop();
        int bottom = top + titleHeight;
        c.drawRect(left, top, right, bottom, backgroundPaint);
        float x = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,10,mContext.getResources().getDisplayMetrics());
        float y = bottom - (titleHeight - textHeight) / 2 - textBaselineOffset;//计算文字baseLine
        c.drawText(title, x, y, textPaint);
        if(flag){
            //还原画布为初始状态
            c.restore();
        }
    }

    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        int pos = parent.getChildViewHolder(view).getAdapterPosition();
        if (titles.containsKey(pos)) {  // 头部偏移
            outRect.set(0, titleHeight, 0, 0);
        } else {
            outRect.set(0, dividerHeight, 0, 0);
        }
    }

    private void drawVertical(Canvas canvas, RecyclerView parent) {
        int left = parent.getPaddingLeft();
        int right = parent.getWidth() - parent.getPaddingRight();
        int top, bottom;
        for (int i = 0; i < parent.getChildCount(); i++) {
            View child = parent.getChildAt(i);
            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
            if (!titles.containsKey(params.getViewLayoutPosition())) {  // 此时画普通分割线
                top = child.getTop() - params.topMargin - dividerHeight;
                bottom = top + dividerHeight;
                mDivider.setBounds(left, top, right, bottom);
                mDivider.draw(canvas);
            } else {
                top = child.getTop() - params.topMargin - titleHeight;
                bottom = top + titleHeight;
                canvas.drawRect(left, top, right, bottom, backgroundPaint);
                float x = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, mContext.getResources().getDisplayMetrics());
                float y = bottom - (titleHeight - textHeight) / 2 - textBaselineOffset;//计算文字baseLine
                canvas.drawText(titles.get(params.getViewLayoutPosition()).toString(), x, y, textPaint);
            }
        }
    }

    private void getTitles(List<AppointDTO> data) {
        if (data.isEmpty()) return;
        int index = 0;  // 索引记录分组第一个的位置
        Date preDate = null;
        for (AppointDTO dto : data) {
            Date date = dto.getFreeClassroomEntity().getFreeDate();
            if (index == 0) {
                this.titles.put(index++, date);
                preDate = date;
                continue;
            }
            if (date.before(preDate)) { // 如果日期早于之前一个说明是另一天的 需要分组
                this.titles.put(index++, date);
                preDate = date;
            } else {    // 否则，索引增加
                index++;
            }
        }
    }

    private String getTitle(int position) {
        while (position >= 0) {
            if (titles.containsKey(position)) {
                return titles.get(position).toString();
            }
            position--;
        }
        return null;
    }

    public void setTitleHeight(int titleHeight) {
        this.titleHeight = titleHeight;
    }
}
